package com.surveycomp.servlets;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;

import com.google.appengine.api.datastore.Key;
import com.surverycomp.models.Event;
import com.surverycomp.models.User;
import com.surveycomp.datastore.PMF;

public class PullWinnerUserServlet extends HttpServlet {
	private static final long serialVersionUID = 2863830513271638261L;

	@SuppressWarnings("unchecked")
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		HttpSession session = req.getSession(true);
		Event event = (Event) session.getAttribute("event");
		PersistenceManager pmf = PMF.get().getPersistenceManager();
		event = (Event) pmf.getObjectById(Event.class, event.getKey());
		Query challengeQuery = pmf.newQuery(User.class);
		challengeQuery.setFilter("event == keyParam");
		challengeQuery.declareParameters(Key.class.getName() + " keyParam");

		List<User> users = (List<User>) challengeQuery.execute(event.getKey());
		try {
			JSONArray array = new JSONArray();
			int i = 0;
			for (User user : users) {
				array.put(i++, user.getJSON());
			}
			resp.getWriter().write(array.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
